package com.sky.controller.backstage;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.BackstageService;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 贾晓晨
 * @version 1.0
 */
@RestController
@RequestMapping("/backstage")
@Slf4j
@Api(tags = "后台管理接口")
public class BackstageController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private BackstageService backstageService;
    @Autowired
    private UserService userService;

    /**
     * 生成登录成功的响应
     * @param user 用户信息
     * @return 登录成功的响应
     */
    private Result<UserLoginVO> generateLoginResponse(User user) {
        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        claims.put(JwtClaimsConstant.Permission, user.getPermission());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        // 构建登录成功返回的VO
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @PostMapping("/login")
    @ApiOperation("admin登录")
    public Result<UserLoginVO> backstageLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = backstageService.login(userLoginDTO);
        return generateLoginResponse(user);
    }

    @GetMapping("/user")
    @ApiOperation("获取用户列表")
    public Result<PageResult> userList(UserPageQueryDTO userPageQueryDTO) {
        PageResult articleList = backstageService.getArticleList(userPageQueryDTO);
        return Result.success(articleList);
    }
    @GetMapping("/user/{id}")
    @ApiOperation("通过id获取用户信息")
    public Result<UserListVO> userStatus(@PathVariable("id") Integer id) {
        UserListVO userListVO = backstageService.getUserInfoById(id);
        return Result.success(userListVO);
    }

    @DeleteMapping("/user/delete")
    @ApiOperation("删除用户")
    public Result deleteUser(@RequestBody List<Integer> ids) {
        backstageService.deleteUser(ids);
        return Result.success("删除成功");
    }

    @PutMapping("/user/update")
    @ApiOperation("修改用户信息")
    public Result updateUserInfo(@RequestBody UserUpdateDTO userUpdateDTO) {
        backstageService.updateUserInfo(userUpdateDTO);
        return Result.success("修改用户信息成功");
    }
    @PostMapping("/user/add")
    @ApiOperation("新增用户")
    public Result addUser(@RequestBody UserBackStageRegisterDTO userBackStageRegisterDTO){
        if (userService.isUsernameExists(userBackStageRegisterDTO.getUsername())!=null) {
            return Result.error(MessageConstant.USERNAME_SOLE);
        }
        if (userService.isEmailExists(userBackStageRegisterDTO.getEmail())!=null) {
            return Result.error(MessageConstant.EMAIL_SOLE);
        }
        // 注册
        backstageService.register(userBackStageRegisterDTO);
        return Result.success("新增用户成功");
    }

    @PutMapping("/userStatus")
    @ApiOperation("更改用户权限")
    public Result userStatus(@RequestBody UserStatusDTO userStatusDTO){
        backstageService.setUserStatus(userStatusDTO);
        return Result.success("更改用户权限成功");
    }

    @GetMapping("/getDict")
    @ApiOperation("获取字典")
    public Result<PageResult> getDict(DictPageQueryDTO dictPageQueryDTO){
        PageResult dictList = backstageService.getDict(dictPageQueryDTO);
        return Result.success(dictList);
    }
    @GetMapping("/getDictInfo/{id}")
    @ApiOperation("获取字典详情")
    public Result<DictVO> getDictInfo(@PathVariable("id") Integer id){
        DictVO dictVO = backstageService.getDictInfo(id);
        return Result.success(dictVO);
    }
    @PutMapping("/updateDict")
    @ApiOperation("修改字典信息")
    public Result updateDict(@RequestBody BackstageDictUpdate backstageDictUpdate){
        backstageService.updateDict(backstageDictUpdate);
        return Result.success("修改字典成功");
    }
    @PutMapping("/updateSatus")
    @ApiOperation("修改字典状态")
    public Result updateStatus(@RequestBody BackstageDictStatusUpdate backstageDictStatusUpdate){
        backstageService.updateDictStatusUpdate(backstageDictStatusUpdate);
        return Result.success("修改字典状态成功");
    }
    @PostMapping("/addDict")
    @ApiOperation("新增字典")
    public Result addDict(@RequestBody BackstageDictAdd backstageDictAdd){
        backstageService.addDict(backstageDictAdd);
        return Result.success("新增成功");
    }

    @PostMapping("/getDictDetails")
    @ApiOperation("获取字典内容详情")
    public Result<PageResult> getDictDetails(@RequestBody BackstageDictQueryPage backstageDictQueryPage){
        PageResult dictDetailVO = backstageService.getDictDetails(backstageDictQueryPage);
        return Result.success(dictDetailVO);
    }

    @PostMapping("/addDictDetails")
    @ApiOperation("新增字典详情")
    public Result addDictDetails(@RequestBody BackstageDictDetailsAdd backstageDictDetailsAdd){
        backstageService.addDictDetails(backstageDictDetailsAdd);
        return Result.success("新增成功");
    }

    @PostMapping("/updateDictDetails")
    @ApiOperation("修改字典详情")
    public Result updateDetails(@RequestBody BackstageDictDetailsUpdateDTO backstageDictDetailsUpdateDTO){
        backstageService.updateDictDetails(backstageDictDetailsUpdateDTO);
        return Result.success("修改成功");
    }

    @GetMapping("/getDictDetailsById/{id}")
    @ApiOperation("通过id获取字典详情")
    public Result<DictInfoVO> getDictDetailsById(@PathVariable("id") Integer id){
        DictInfoVO dictInfoVO =  backstageService.getDictDetailsById(id);
        return Result.success(dictInfoVO);
    }

    @DeleteMapping("/deleteDictDetail")
    @ApiOperation("删除字典详情")
    public Result deleteDictDetail(@RequestBody List<Integer> ids) {
        backstageService.deleteDictDetail(ids);
        return Result.success("删除字典详情成功");
    }

    @DeleteMapping("/deleteDict")
    @ApiOperation("删除字典及其内容")
    public Result deleteDict(@RequestBody List<Integer> ids) {
        backstageService.deleteDictDetailByDictId(ids);
        backstageService.deleteDict(ids);
        return Result.success("删除字典详情成功");
    }

    @GetMapping("/getDictDetailsBydictName/{str}")
    @ApiOperation("通过dictName获取字典详情")
    public Result<List<DictInfoVO>> getDictDetailsBydictName(@PathVariable("str") String str){
        List<DictInfoVO> dictInfoVO =  backstageService.getDictDetailsBydictName(str);
        return Result.success(dictInfoVO);
    }

}
